package com.lagou.filter;

import com.lagou.pojo.IpManager;
import com.lagou.pojo.IpMonitor;
import com.lagou.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private IpManager ipManager;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String ipAddr = IpUtil.getIpAddr(request);

        IpMonitor ipStatistics = IpMonitor.builder()
                .ip(ipAddr)
                .createTime(System.currentTimeMillis())
                .build();

        ipManager.addIpMonitor(ipStatistics);

        if(ipManager.isAccess(ipAddr)) {
            return chain.filter(exchange);
        }else {
            byte[] bits = "您频繁访问，请求已被拒绝".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            response.setStatusCode(HttpStatus.SEE_OTHER);
            return response.writeWith(Mono.just(buffer));
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }

}
